<template>
  <div class="tp-box">
    <a-drawer
      :visible="props.visible"
      :width="props.width"
      :closable="props.closable"
      :destroyOnClose="props.destroyOnClose"
      @close="handleClose"
    >
      <template #title>
        <div class="title-detail">
          <Tooltip placement="top">
            <template #title>
              <span>{{ getTipTitle }}</span>
            </template>
            <h3>{{ getTitle }}</h3>
          </Tooltip>
          <h2 style="">
            <div class="table-settings">
              <ImportSetting
                :tableData="computedTableData"
                :tableColumns="computedTableColumn"
                :wscolsList="props.wscolsList"
                ref="ImporBusinessDom"
                excelName="明细表"
                @click="importBusinessFn"
              />
            </div>
          </h2>
        </div>
      </template>

      <!-- :scroll="{ x: 1500, y: 600 }" -->
      <a-table
        :columns="computedTableColumn"
        :data-source="computedTableData"
        :page-size-options="pageSizeOptions"
        :loading="loading"
        bordered
        :pagination="false"
        size="middle"
        :scroll="{ x: 'calc(700px + 50%)', y: props.detailTableHeight }"
      >
        <!-- <template #action>
          <a>action</a>
        </template> -->
      </a-table>
      <div class="pagination">
        <a-pagination
          show-size-changer
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          @show-size-change="onShowSizeChange"
        />
      </div>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
  import { Tooltip } from 'ant-design-vue';
  import { watchEffect, ref, computed, onMounted, watch } from 'vue';
  import ImportSetting from '../../housesDangerBusiness/ImportSetting.vue';
  import { getGeneralDetailList } from '/@/api/demo/system';
  import {
    downloadByUrl,
    downloadByData,
    downloadByBase64,
    downloadByOnlineUrl,
  } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  import { useUserStore } from '/@/store/modules/user';
  // 表格的 ref Dom名称
  const ImporBusinessDom: any = ref(null);
  // 默认传过来的值q
  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    width: {
      type: Number,
      default: 256,
    },
    detailTableHeight: {
      type: Number,
      default: 600,
    },
    hzfs: {
      type: String,
      default: '',
    },
    closable: {
      type: Boolean,
      default: true,
    },
    data: {
      type: Array,
      default: () => [],
    },
    detailParams: {
      type: Object,
      default: () => {},
    },
    currentXzqdmname: {
      type: String,
      default: '',
    },
    currentTitle: {
      type: String,
      default: '',
    },
    wscolsList: {
      type: Array,
      default: () => [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
    },
    destroyOnClose: {
      type: Boolean,
      default: true,
    },
    onClose: {
      type: Function as PropType<() => void>,
      default: () => {},
    },
  });
  let pageIndex = ref(1);
  let pageSize = ref(10);
  let loading = ref(false);
  const pageSizeOptions = ref<string[]>(['10', '20', '50', '100']);
  let tableSource = ref([]);
  let total = ref(0);
  const columns = [
    { title: '序号', width: 50, dataIndex: 'index', key: 'index', align: 'center', fixed: 'left' },
    { title: '行政区', dataIndex: 'xzqdmname', key: 'xzqdmname', align: 'center', width: 70 },
    { title: '街道', dataIndex: 'townname', key: 'townname', align: 'center', width: 120 },
    { title: '村', dataIndex: 'villagename', key: 'villagename', align: 'center', width: 120 },
    { title: '地址', dataIndex: 'address', key: 'address', width: 240 },
    { title: '房屋编号', dataIndex: 'fwbh', key: 'fwbh', width: 140 },
    { title: '场所名称', dataIndex: 'csmc', key: 'csmc', width: 90 },
    { title: '场所类型', dataIndex: 'cstype', key: 'cstype', width: 90 },
    { title: '发现人员', dataIndex: 'yhfx_name', key: 'yhfx_name', width: 90, show: 'false' },
    {
      title: '发现时间',
      dataIndex: 'yhfx_time',
      key: 'yhfx_time',
      width: 180,
      customRender: ({ value }) => {
        if (value) {
          let time = formatDate(value);
          return time;
        } else {
          return value;
        }
      },
    },
    { title: '消隐人员', dataIndex: 'yhxc_name', key: 'yhxc_name', width: 90 },
    {
      title: '消隐时间',
      dataIndex: 'yhxc_time',
      key: 'yhxc_time',
      width: 180,
      customRender: ({ value }) => {
        if (value) {
          let time = formatDate(value);
          return time;
        } else {
          return value;
        }
      },
    },
    // { title: '核查人员', dataIndex: 'hcry_name', key: 'hcry_name', width: 90 },
    // { title: '隐患数量', dataIndex: 'prosum', key: 'prosum', align: 'center', width: 50 },
    // { title: 'Column 6', dataIndex: 'address', key: '6', width: 150 },
    // {
    //   title: 'Action',
    //   key: 'operation',
    //   fixed: 'right',
    //   width: 100,
    //   slots: { customRender: 'action' },
    // },
  ];
  // 计算属性，用于实时更新数据到页面上
  const computedTableColumn = computed(() => {
    let newColumn: any = [];
    if (props.hzfs === '2') {
      newColumn = columns.filter(
        (column) =>
          column.key !== 'cstype' &&
          column.key !== 'place_name' &&
          column.key !== 'yhfx_name' &&
          column.key !== 'yhfx_time' &&
          column.key !== 'yhxc_name' &&
          column.key !== 'yhxc_time',
      );
      return newColumn;
    } else {
      newColumn = columns;
    }
    return newColumn;
  });
  const computedTableData = computed(() => {
    return tableSource.value;
  });
  const getTitle = computed(() => {
    // let str = `【${props.currentXzqdmname} 】-- ${props.currentTitle}`;
    let str = `隐患项：${props.currentTitle}`;
    console.log('lenght', str.length);
    if (str.length > 50) {
      str = str.substring(0, 50) + '...';
    }
    return str;
  });
  const getTipTitle = computed(() => {
    let str = `${props.currentTitle}`;
    return str;
  });
  watch(
    () => props.visible,
    (newVal, oldVal) => {
      // console.log(`visible 变化了，新值：${newVal}，旧值：${oldVal}`);
      // 在这里执行你需要的操作
      if (newVal) {
        console.log('@参数', props.detailParams);
        getTableData();
      }
    },
  );
  const getTableData = async () => {
    let params: any = {
      pageindex: pageIndex.value,
      pagesize: pageSize.value,
      ...props.detailParams,
    };
    loading.value = true;
    let res = await getGeneralDetailList(params);
    loading.value = false;
    let list = res.items;
    list.forEach((item, index) => {
      item.index = ++index;
    });
    tableSource.value = list;
    total.value = res.total;
    // console.log('@resqqq', list);
  };
  //  调用 父组件传过来的方法
  const emit = defineEmits(['close']);
  // 导出
  const importBusinessFn = () => {
    // if (ImporBusinessDom.value) {
    //   ImporBusinessDom.value.importFn();
    // }
    // 后端导出
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const userStore = useUserStore();
    const tk = userStore.getToken;
    const { type_zx, groupbyLever, groupbyLever_code, groupbyLever_code_project } =
      props.detailParams;
    let url = `${uriBase}/admin/custom-function/GeneralDetail_Import?access_token=${tk}&type_zx=${type_zx}&groupbyLever=${groupbyLever}&groupbyLever_code=${groupbyLever_code}&groupbyLever_code_project=${groupbyLever_code_project}`;
    downloadByUrl({
      url: url,
      target: '_blank',
    });
  };
  const formatDate = (date: string): string => {
    const T2 = date.replace('T', ' ');
    return T2;
  };
  const handleClose = () => {
    emit('close');
    pageIndex.value = 1;
    pageSize.value = 10;
  };
  // 切换页码的时候更新  pageIndex 和  pageSize
  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    // antDesign  自动给  pageIndex 和 pageSize 赋值
    // pageIndex.value = pageIndex;
    // pageSize.value = pageSize;
    // console.log('@pageIndex,pageSize', pageIndex, pageSize);
  };
  watch(pageSize, () => {
    // console.log('pageSize', pageSize.value);
    getTableData();
  });
  watch(pageIndex, () => {
    // console.log('current', pageIndex.value);
    getTableData();
  });
  onMounted(() => {});
</script>
<style lang="less" scoped>
  .tp-box {
    height: 100%;
  }
  .title-detail {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .pagination {
    margin-top: 5px;
    display: flex;
    justify-content: flex-end;
  }
</style>
